package swingxrcp.framework.server.action;

import java.io.Serializable;
import java.util.List;

import swingxrcp.framework.model.Action;

/**
 * 拦截器链
 *
 * @author liangfei
 *
 */
public class ActionInterceptorChain implements ActionInterceptor {

	// 当前拦截器
	private final ActionInterceptor currentActionInterceptor;

	// 下一拦截器
	private final ActionInterceptor nextActionInterceptor;

	/**
	 * 构造拦截器链
	 *
	 * @param currentActionInterceptor 当前拦截器
	 * @param nextActionInterceptor 下一拦截器
	 */
	public ActionInterceptorChain(ActionInterceptor currentActionInterceptor, ActionInterceptor nextActionInterceptor) {
		if (currentActionInterceptor == null)
			throw new NullPointerException("currentActionInterceptor == null");
		this.currentActionInterceptor = currentActionInterceptor;
		this.nextActionInterceptor = nextActionInterceptor;
	}

	public Serializable intercept(Action action, Serializable object) {
		if (nextActionInterceptor == null)
			return currentActionInterceptor.intercept(action, object); // 如果没有下一拦载器，传入实际Action实例
		return currentActionInterceptor.intercept(new ActionProxy(nextActionInterceptor, action), object); // 如果有下一拦载器，则代理下一拦截器
	}

	/**
	 * 将拦截器列表归约成链
	 *
	 * @param sctionInterceptors 拦截器列表
	 * @return 拦截器链的第一个拦截器
	 */
	public static ActionInterceptor reduceActionInterceptorChain(List<ActionInterceptor> actionInterceptors) {
		if (actionInterceptors == null || actionInterceptors.size() == 0)
			return null;
		ActionInterceptor lastActionInterceptor = null;
		for (int i = actionInterceptors.size() - 1; i >= 0; i --) { // 倒序拼装拦截器链
			ActionInterceptor actionInterceptor = actionInterceptors.get(i);
			if (actionInterceptor != null)
				lastActionInterceptor = new ActionInterceptorChain(actionInterceptor, lastActionInterceptor);
		}
		return lastActionInterceptor;
	}

}
